<template>
  <div class="article-comments">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <article-val :list="list"/>
    </van-list>
  </div>
</template>

<script>
// 2. 导入接口
import {getComments} from '@/api/comment'
import ArticleVal from './article-val.vue'
import Bus from '@/utils/bus'

export default {
  name: 'test-box',
  components: {
    ArticleVal
  },
  props: {
    articleId: {
      type: [String, Number],
      required: true
    },
    type: {
      default: 'a'
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      offset: null
    }
  },
  created() {
    if(this.type === 'a') {
      this.onLoad()
    }

    this.getObj()
  },
  methods: {
    // 4. 页面请求数据
    async onLoad() {
      try {
        // 5. 准备传递给后台的参数
        let params = {
          type: this.type,  // a 给文章的评论
          source: this.articleId,  // 文章ID
          offset: this.offset,  // 翻页
          limit: 10  // 每一页的个数
        }

        // 6. 发起请求， 并解构返回的的数据
        //   last_id 下一页的标识
        //   results 数据
        //   total_count 总条数
        const {data: {data: {last_id, results, total_count}}} = await getComments(params)

        // 7. 把数据赋值给 list
        this.list = [...this.list, ...results]
        this.offset = last_id
        // 8. 关闭loading效果
        this.loading = false

        // 进行子组件给父组件传值
        this.$emit('changeTotalCount', total_count)

        // 9. 判断数据是否加载完成
        if(this.list.length >= total_count) {
          // 10. 全部加载完成 给出 提示
          this.finished = true
        }
      } catch(err) {
        console.log(err)
      }
    },
    getObj() {
      Bus.$on('submitObj', res => {
        this.list.unshift(res)
      })
    }

  }
}
</script>

<style>

</style>
